# Google Apps API Wrapper copyright 2008-2009 Michael De Soto. This program is 
# distributed under the terms of the GNU General Public License, version 3.
#
# $Id: Provisioning.pm 4 2008-10-29 01:05:22Z mdesoto@quarghost.com $

package Google::Provisioning;

use LWP::UserAgent;

use strict;
use warnings;

our $VERSION = '0.01';

sub new {
    my $this = shift;
    my $class = ref($this) || $this;
    my (%tokens) = @_;

    my $self;
    foreach (keys %tokens) {
        $self->{$_} = $tokens{$_};
    }
    
    bless $self, $class;
    $self;
}

sub is_authorized {
    my $self = shift;
    my ($ctx) = @_;
    
    my $domain = $self->{$ctx};
    return unless $domain;
    
    my $token = $domain->{token};
    my $token_timestamp = $domain->{token_timestamp};

    # 86400 should be the seconds in a day. Needs to be in config file.
    unless ( ($token) && ((time - $token_timestamp) < 86400) ) {
        return $self->login($domain);
    } else {
        return 1
    }
}

sub login {
    my $self = shift;
    my ($domain) = @_;
    
    my $ua = LWP::UserAgent->new;
    
    # $url should be in constant variable or config file;
    my $url = 'https://www.google.com/accounts/ClientLogin';
    my $response = $ua->post( $url,
        [ 'accountType' => 'HOSTED',
          'Email' => $domain->{administrator},
          'Passwd' => $domain->{password},
          'service' => 'apps'
        ]
    );
    
    return 0 unless $response->is_success;
    
    foreach (split/\n/, $response->content) {
        if (m/^Auth=(.+)$/) {
            $domain->{token} = $1;
            $domain->{token_timestamp} = time;
            last;
        }
    }
    return 1;
}

sub delete {
    my $self = shift;
    my ($user) = @_;
    
    # Next three lines are the same as in update(). Needs to be fixed.
    my @address =  parse_email($user->{username});
    my $username = $address[0];
    my $domain = $address[1];
    
    my $xml = undef;
    
    my $url = "https://apps-apis.google.com/a/feeds/$domain/user/2.0/$username";
    $self->request('DELETE', $url, $xml, $domain);
}

sub update {
    my $self = shift;
    my ($user) = @_;
    
    # If no username is passed, then we don't know what context we're in. Throw an error.
    # Error routine here

    # This is ugly too
    my @address =  parse_email($user->{username});
    my $username = $address[0];
    my $domain = $address[1];
   
    
    my $xml = qq|<?xml version="1.0" encoding="UTF-8"?>|;
    $xml .= qq|<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">|;
    $xml .= qq|<atom:category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/apps/2006#user"/>|;
    if ($user->{password} || $user->{suspended}) {
        $xml .= qq|<apps:login|;
        $xml .= qq| username="$username"| if $username; # Do we need this one?
        $xml .= qq| password="$user->{password}"| if $user->{password};
        
        # Need more elegant solution to true/false here. Right now we have to pass a value
        # if no password is sent as well. This is fundamentally wrong.
        if ($user->{suspended} eq 'true') {
            $xml .= qq| suspended="true"|;
        } else {
            $xml .= qq| suspended="false"|;
        }
    $xml .= qq|/>|;
    }
    $xml .= qq|<apps:quota limit="$user->{quota}"/>| if $user->{quota};
    if ($user->{family_name} || $user->{given_name}) {
        $xml .= qq|<apps:name|;
        $xml .= qq| familyName="$user->{family_name}"| if $user->{family_name};
        $xml .= qq| givenName="$user->{given_name}" | if $user->{given_name};
        $xml .= qq|/>|;
    }
    $xml .= qq|</atom:entry>|;
    
    
    #
    print "$xml\n\n";
    
    my $url = "https://apps-apis.google.com/a/feeds/$domain/user/2.0/$username";
    $self->request('PUT', $url, $xml, $domain);
    # This may be changed in the future to $self->request($domain, $user, $xml);
#    print "url\n\n";
}


sub request {
    my $self = shift;
	my($method, $url, $xml, $ctx) = @_;
    
#	return unless $self->is_authorized;
	print "Not authorized\n\n\n" unless $self->is_authorized($ctx);
    my $domain = $self->{$ctx};
	
#	$xml = encode('UTF-8', $xml)    

    my $ua = LWP::UserAgent->new;
	my $request = HTTP::Request->new($method => $url);

    $request->header('Content-type' => 'application/atom+xml');
    $request->header('Authorization' => qq|GoogleLogin auth=$domain->{token}|);
    $request->content($xml) if $xml;
    
    my $response = $ua->request($request);
#
    print $response->content;
    print "\n\n";

}

# The following two (should be three) functions should go in Utils.pm

sub parse_email{
    my ($suspect) = @_;
    return unless $suspect;

    my @parts = split(/\@/, $suspect);
    return unless scalar(@parts) == 2;
	
    my $username = is_username($parts[0]);
    return unless (($username) && ($username eq $parts[0]));

    # Must write test for domain.
    my $domain = $parts[1];
    return unless ($domain && ($domain eq $parts[1]));

    my @email = ($username, $domain);
    return @email;
}

sub is_username{
    my ($suspect) = @_;
    return unless $suspect;

    my ($username) = $suspect =~ /^([a-z0-9_\-\.]+)$/i;
    return $username;
}

1;
__END__

=head1 NAME

Google::Provisioning - Perl extension for blah blah blah

=head1 SYNOPSIS

  use Google::Provisioning;
  blah blah blah

=head1 DESCRIPTION

Stub documentation for Google::Provisioning, created by h2xs. It looks like the
author of the extension was negligent enough to leave the stub
unedited.

Blah blah blah.

=head2 EXPORT

None by default.



=head1 SEE ALSO

Mention other useful documentation such as the documentation of
related modules or operating system documentation (such as man pages
in UNIX), or any relevant external documentation such as RFCs or
standards.

If you have a mailing list set up for your module, mention it here.

If you have a web site set up for your module, mention it here.

=head1 AUTHOR

Michael De Soto, E<lt>mdesoto@localdomainE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2008 by Michael De Soto

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.0 or,
at your option, any later version of Perl 5 you may have available.


=cut
